package com.jade.store.wechat.service.impl;

import com.jade.bss.base.customer.Customer;
import com.jade.bss.db.impl.BaseFacadeImpl;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.store.wechat.biz.business.GetAuthorizerInfoBusiness;
import com.jade.store.wechat.biz.business.GetPreAuthCodeBusiness;
import com.jade.store.wechat.biz.business.QueryAuthBusiness;
import com.jade.store.wechat.biz.common.Configure;
import com.jade.store.wechat.biz.common.WxConstantUtil;
import com.jade.store.wechat.biz.protocol.auth.*;
import com.jade.store.wechat.biz.protocol.auth.queryAuth.QueryFuncInfo;
import com.jade.store.wechat.biz.service.auth.PushComponentAuthService;
import com.jade.store.wechat.dao.WechatAuthPushDao;
import com.jade.store.wechat.dao.WechatAppDao;
import com.jade.store.wechat.entity.WXAuthPush;
import com.jade.store.wechat.entity.WXPreAuthCode;
import com.jade.store.wechat.entity.WechatApp;
import com.jade.store.wechat.service.WechatAuthFacade;
import com.jade.zsy.base.common.CacheServiceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * User: JinYa 2009_jinya@163.com
 * Date: 2016-5-5
 * Time: 10:53
 * Version : 1.0
 * Remark:
 * History:
 */
@Service("WechatAuthFacade")
public class WechatAuthFacadeImpl extends BaseFacadeImpl implements WechatAuthFacade {
    @Inject
    @Named("WechatAppDao")
    private WechatAppDao wechatAppDao;
    @Inject
    @Named("WechatAuthPushDao")
    private WechatAuthPushDao wechatAuthPushDao;

    @Transactional(propagation= Propagation.REQUIRED)
    public void AuthPush(HttpServletRequest request) throws Exception{
        AuthPush entity= PushComponentAuthService.getReceiveauthcode(request);
        if(entity==null)return;
        WXAuthPush newTicket=new WXAuthPush();
        newTicket.setAppId(entity.getAppId());
        newTicket.setComponentVerifyTicket(entity.getComponentVerifyTicket());
        newTicket.setCreateTimeStr(entity.getCreateTime());
        newTicket.setInfoType(entity.getInfoType());
        newTicket.setAuthorizationCode(entity.getAuthorizationCode());
        newTicket.setAuthorizationCodeExpiredTime(entity.getAuthorizationCodeExpiredTime());
        newTicket.setAuthorizerAppid(entity.getAuthorizerAppid());
        wechatAuthPushDao.save(newTicket);
        if(newTicket.getInfoType().equals("unauthorized") && StringUtils.isNotEmpty(newTicket.getAuthorizerAppid())){
            Criteria criteria = new Criteria();
            criteria.add(Restrictions.eq("authorizer_appid", newTicket.getAuthorizerAppid()));
            PagingList<WechatApp> list = wechatAppDao.queryEntity(WechatApp.class,criteria);
            if(list!=null && list.size()>0){
                for(WechatApp app : list){
                    app.setStatus(WechatApp.STATUS_CANCEL);
                    wechatAppDao.update(app);
                }
            }
        }else if( newTicket.getInfoType().equals("authorized") && StringUtils.isNotEmpty(newTicket.getAuthorizerAppid()) && newTicket.getAuthorizerAppid().equals("wx570bc396a51b8ff8")){
            Customer customer=new Customer();
            customer.setOwnerId("-1");
            customer.setId(-1);
            customer.setName("sys");
            WechatAuthFacade wechatAuthFacade = ApplicationContextUtils.getBean("WechatAuthFacade");
            wechatAuthFacade.InitWechatApp(customer,request,newTicket.getAuthorizationCode(),"");
        }
    }

    @Transactional(propagation= Propagation.REQUIRED)
    public WXPreAuthCode get_pre_auth_code(HttpServletRequest request) throws Exception{
        PreAuthCodeCodeRes obj= (new GetPreAuthCodeBusiness()).run(new PreAuthCodeCodeReq(Configure.appID),null);
        if(obj==null) return null;
        WXPreAuthCode entity=new WXPreAuthCode();
        entity.setPre_auth_code(obj.getPre_auth_code());
        entity.setExpires_in(obj.getExpires_in());
        entity.setComponent_appid(Configure.appID);
       return entity;
    }
    @Transactional(propagation= Propagation.REQUIRED)
    public void InitWechatApp(Customer customer,HttpServletRequest request,String auth_code,String expires_in) throws Exception {
        if(StringUtils.isEmpty(auth_code))
            return;
        CacheServiceUtil.set(request, WxConstantUtil.cache_authorization_code, auth_code, 100);
        WechatApp wechatApp=new WechatApp();
        //使用授权码换取公众号的接口调用凭据和授权信息
        QueryAuthReq req=new QueryAuthReq();
        req.setComponent_appid(Configure.appID);
        req.setAuthorization_code(auth_code);
        QueryAuthRes res= (new QueryAuthBusiness()).run(req);
        wechatApp.setCreatorId(customer.getId());
        wechatApp.setCreator(customer.getName());
        wechatApp.setOwnerId(customer.getOwnerId());
        if(res.getAuthorization_info()!=null){
            wechatApp.setAuthorizer_appid(res.getAuthorization_info().getAuthorizer_appid());
            wechatApp.setAuthorizer_access_token(res.getAuthorization_info().getAuthorizer_access_token());
            wechatApp.setAuthorizer_refresh_token(res.getAuthorization_info().getAuthorizer_refresh_token());
            if(res.getAuthorization_info().getFunc_info()!=null &&  res.getAuthorization_info().getFunc_info().length>0){
                 for(QueryFuncInfo queryFuncInfo : res.getAuthorization_info().getFunc_info()){
                     if(StringUtils.isEmpty(wechatApp.getBase_func_info()))
                         wechatApp.setBase_func_info(queryFuncInfo.getFuncscope_category().getId());
                     else
                         wechatApp.setBase_func_info(wechatApp.getBase_func_info()+","+queryFuncInfo.getFuncscope_category().getId());
                 }
            }
        }
        //获取授权方的公众号帐号基本信息
        if(StringUtils.isNotEmpty(wechatApp.getAuthorizer_appid())){
            GetAuthorizerInfoReq getAuthorizerInfoReq=new GetAuthorizerInfoReq();
            getAuthorizerInfoReq.setComponent_appid(Configure.appID);
            getAuthorizerInfoReq.setAuthorizer_appid(wechatApp.getAuthorizer_appid());
            GetAuthorizerInfoRes getAuthorizerInfoRes=(new GetAuthorizerInfoBusiness()).run(getAuthorizerInfoReq);
            if(getAuthorizerInfoRes.getAuthorizer_info()!=null){
                wechatApp.setNick_name(getAuthorizerInfoRes.getAuthorizer_info().getNick_name());
                wechatApp.setPrincipal_name(getAuthorizerInfoRes.getAuthorizer_info().getPrincipal_name());
                wechatApp.setHead_img(getAuthorizerInfoRes.getAuthorizer_info().getHead_img());
                wechatApp.setService_type_info(getAuthorizerInfoRes.getAuthorizer_info().getService_type_info());
                wechatApp.setVerify_type_info(getAuthorizerInfoRes.getAuthorizer_info().getVerify_type_info());
                wechatApp.setUser_name(getAuthorizerInfoRes.getAuthorizer_info().getUser_name());
                wechatApp.setAlias(getAuthorizerInfoRes.getAuthorizer_info().getAlias());
                wechatApp.setBusiness_info(getAuthorizerInfoRes.getAuthorizer_info().getBusiness_info());
                wechatApp.setQrcode_url(getAuthorizerInfoRes.getAuthorizer_info().getQrcode_url());
            }
            if(getAuthorizerInfoRes.getAuthorization_info()!=null){
                wechatApp.setAppid(getAuthorizerInfoRes.getAuthorization_info().getAppid());
                if(getAuthorizerInfoRes.getAuthorization_info().getFunc_info()!=null &&  getAuthorizerInfoRes.getAuthorization_info().getFunc_info().length>0){
                    for(QueryFuncInfo queryFuncInfo : getAuthorizerInfoRes.getAuthorization_info().getFunc_info()){
                        if(StringUtils.isEmpty(wechatApp.getFunc_info()))
                            wechatApp.setFunc_info(queryFuncInfo.getFuncscope_category().getId());
                        else
                            wechatApp.setFunc_info(wechatApp.getFunc_info()+","+queryFuncInfo.getFuncscope_category().getId());
                    }
                }
            }
        }
        wechatAppDao.save(wechatApp);
    }
}
